﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using MayhemCore;
using MayhemWpf.ModuleTypes;
using MayhemWpf.UserControls;
using Microsoft.WindowsAPICodePack.Sensors;
using SensorHOL;
using SensorMayhem.Wpf;

namespace SensorMayhem.Events
{
    [DataContract]
    [MayhemModule("Sensor: Light", "Triggers above or under a specific light level")]
    public class Light : EventBase, IWpfConfigurable
    {
        SensorHelper<AmbientLightSensor, LuminousIntensity> _lightSensor;

        private bool triggered = false;

        [DataMember]
        private int ligthLevel;

        [DataMember]
        private bool greater;

        protected override void OnLoadDefaults()
        {
            ligthLevel = 10;
        }

        protected override void OnEnabling(EnablingEventArgs e)
        {
            try
            {
                _lightSensor = new SensorHelper<AmbientLightSensor, LuminousIntensity>();
                _lightSensor.Initialize();
                _lightSensor.PropertyChanged +=new System.ComponentModel.PropertyChangedEventHandler(_lightSensor_PropertyChanged);
            }
            catch(Exception)
            {
            
            }
            
        }

        void _lightSensor_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            bool trigger = greater ? (_lightSensor.Value.Intensity > ligthLevel) : (_lightSensor.Value.Intensity < ligthLevel);
            if (!triggered && trigger)
            {
                Trigger();
                triggered = true;
            }
            else if (!trigger)
            {
                ResetTrigger();
            }
        }
        
        protected override void OnDisabled(DisabledEventArgs e)
        {
            try
            {
                _lightSensor.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(_lightSensor_PropertyChanged);
            }
            catch(Exception)
            {
            
            }
            ResetTrigger();
        }

        private void ResetTrigger()
        {
            triggered = false;
        }

        public WpfConfiguration ConfigurationControl
        {
            get
            {
                return new LightConfig(ligthLevel, greater);
            }
        }

        public void OnSaved(WpfConfiguration configurationControl)
        {
            LightConfig config = configurationControl as LightConfig;
            ligthLevel = config.LightLevel;
            greater = config.Greater;

        }

        public string GetConfigString()
        {
            return "Light level " + (greater ? "above" : "below") + " " + ligthLevel.ToString();
        }
    }
}
